package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.util.Date;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Override
    public Date getExpireTimeByEmailAndCode(String email, String code) {
        User user = new User();
        user.setEmail(email);
        user.setCode(code);
        Example<User> example = Example.of(user);
        return userDao.findOne(example).get().getExpiretime();
    }

    @Override
    public boolean getIsRegisteredByEmail(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example<Token> example = Example.of(token);
        Optional<Token> optional= tokenDao.findOne(example) ;
        if(optional.isPresent()){
            return true;
        }
        return false;
    }

    @Override
    public void saveTokenByEmail(String email, String token) {
        Token tokenToken = new Token();
        tokenToken.setEmail(email);
        tokenToken.setToken(token);
        tokenDao.save(tokenToken);
    }

    @Override
    public String getEmailInfoByToken(String token) {
        Token tokenToken = new Token();
        tokenToken.setToken(token);
        Example<Token> example = Example.of(tokenToken);
        return tokenDao.findOne(example).get().getEmail();
    }
}
